<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    style="top:20px;height: 95%;">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">保存并审核</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">保存</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据编号">
              <a-input placeholder="请输入单据编号" v-decorator.trim="[ 'number' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-button @click="handleImportForBom">引入Bom清单</a-button>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24"></a-col>
        </a-row>
        <j-editable-table id="billModal"
                          :ref="refKeys[0]"
                          :loading="materialTable.loading"
                          :columns="materialTable.columns"
                          :dataSource="materialTable.dataSource"
                          :minWidth="minWidth"
                          :maxHeight="300"
                          :rowNumber="false"
                          :rowSelection="true"
                          :actionButton="true"
                          @valueChange="onValueChange"
                          @added="onAdded"
                          @deleted="onDeleted">
          <template #buttonAfter>
            <a-row :gutter="24" style="float:left;" data-step="4" data-title="扫码录入" data-intro="此功能支持扫码枪扫描商品条码进行录入">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">扫码录入</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input placeholder="请扫码商品条码并回车" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">收起扫码</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;">
              <a-col :md="24" :sm="24">
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="handleBatchSetDepot">
                      <a-icon type="setting"/>
                      批量设置
                    </a-menu-item>
                    <a-menu-item v-if="isTenant" key="2" @click="addDepot">
                      <a-icon type="plus"/>
                      新增仓库
                    </a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px">仓库操作
                    <a-icon type="down"/>
                  </a-button>
                </a-dropdown>
              </a-col>
            </a-row>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="1" placeholder="请输入备注" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="附件">
              <j-upload v-model="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <select-bom-modal ref="selectBomModal" multi="false" @ok="onSelectBom"></select-bom-modal>
  </j-modal>
</template>
<script>
    import pick from 'lodash.pick'
    import DepotModal from '../../system/modules/DepotModal'
    import BatchSetDepot from '../dialog/BatchSetDepot'
    import { FormTypes } from '@/utils/JEditableTableUtil'
    import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
    import { BillModalMixin } from '../mixins/BillModalMixin'
    import { getAction } from '@/api/manage'
    import { getMpListShort } from '@/utils/util'
    import JUpload from '@/components/jeecg/JUpload'
    import JDate from '@/components/jeecg/JDate'
    import Vue from 'vue'
    import SelectBomModal from '../../production/modules/SelectBomModal'
    import { getBom } from '@/api/api'

    export default {
        name: 'DisassembleModal',
        mixins: [JEditableTableMixin, BillModalMixin],
        components: {
            SelectBomModal,
            DepotModal,
            BatchSetDepot,
            JUpload,
            JDate
        },
        data () {
            return {
                title: '操作',
                width: '1600px',
                moreStatus: false,
                // 新增时子表默认添加几行空数据
                addDefaultRowNum: 1,
                visible: false,
                operTimeStr: '',
                prefixNo: 'CXD',
                fileList: [],
                model: {},
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 8 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 },
                },
                refKeys: ['materialDataTable',],
                activeKey: 'materialDataTable',
                materialTable: {
                    loading: false,
                    dataSource: [],
                    columns: [
                        { title: '商品类型', key: 'mType', width: '7%', type: FormTypes.normal },
                        {
                            title: '仓库名称',
                            key: 'depotId',
                            width: '8%',
                            type: FormTypes.select,
                            placeholder: '请选择${title}',
                            options: [],
                            allowSearch: true,
                            validateRules: [{ required: true, message: '${title}不能为空' }]
                        },
                        {
                            title: '条码',
                            key: 'barCode',
                            width: '10%',
                            type: FormTypes.popupJsh,
                            kind: 'material',
                            multi: true,
                            validateRules: [{ required: true, message: '${title}不能为空' }]
                        },
                        { title: '名称', key: 'name', width: '8%', type: FormTypes.normal },
                        { title: '规格', key: 'standard', width: '7%', type: FormTypes.normal },
                        { title: '型号', key: 'model', width: '7%', type: FormTypes.normal },
                        // {title: '颜色', key: 'color', width: '5%', type: FormTypes.normal},
                        // {title: '扩展信息', key: 'materialOther', width: '5%', type: FormTypes.normal},
                        { title: '库存', key: 'stock', width: '5%', type: FormTypes.normal },
                        { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
                        { title: '多属性', key: 'sku', width: '4%', type: FormTypes.normal },
                        {
                            title: '数量', key: 'operNumber', width: '5%', type: FormTypes.inputNumber, statistics: true,
                            validateRules: [{ required: true, message: '${title}不能为空' }]
                        },
                        { title: '单价', key: 'unitPrice', width: '5%', type: FormTypes.normal, readonly: true },
                        {
                            title: '金额',
                            key: 'allPrice',
                            width: '5%',
                            type: FormTypes.normal,
                            readonly: true,
                            statistics: true
                        },
                        {
                            title: '单价(含税)',
                            key: 'taxUnitPrice',
                            width: '7%',
                            type: FormTypes.inputNumber,
                            statistics: true
                        },
                        {
                            title: '价税合计',
                            key: 'taxLastMoney',
                            width: '7%',
                            type: FormTypes.inputNumber,
                            statistics: true
                        },
                        { title: '备注', key: 'remark', width: '5%', type: FormTypes.input }
                    ]
                },
                confirmLoading: false,
                validatorRules: {
                    operTime: {
                        rules: [
                            { required: true, message: '请输入单据日期!' }
                        ]
                    },
                    type: {
                        rules: [
                            { required: true, message: '请选择类型!' }
                        ]
                    }
                },
                url: {
                    add: '/depotHead/addDepotHeadAndDetail',
                    edit: '/depotHead/updateDepotHeadAndDetail',
                    detailList: '/depotItem/getDetailList'
                },
                lastGroupItemOperNumber: 1
            }
        },
        created () {
            this.$on('onOperNumberValueChange', this.onOperNumberValueChange)
        },
        methods: {
            //调用完edit()方法之后会自动调用此方法
            editAfter () {
                this.billStatus = '0'
                this.changeColumnHide()
                if (this.action === 'add') {
                    this.addInit(this.prefixNo)
                    this.fileList = []
                } else {
                    this.model.operTime = this.model.operTimeStr
                    this.fileList = this.model.fileName
                    this.$nextTick(() => {
                        this.form.setFieldsValue(pick(this.model, 'organId', 'operTime', 'number', 'remark',
                            'discount', 'discountMoney', 'discountLastMoney', 'otherMoney', 'accountId', 'changeAmount'))
                    })
                    // 加载子表数据
                    let params = {
                        headerId: this.model.id,
                        mpList: getMpListShort(Vue.ls.get('materialPropertyList')),  //扩展属性
                        linkType: 'basic'
                    }
                    let url = this.readOnly ? this.url.detailList : this.url.detailList
                    this.requestSubTableData(url, params, this.materialTable)
                }
                //复制新增单据-初始化单号和日期
                if (this.action === 'copyAdd') {
                    this.model.id = ''
                    this.model.tenantId = ''
                    this.copyAddInit(this.prefixNo)
                }
                this.initSystemConfig()
                this.initDepot()
            },
            //提交单据时整理成formData
            classifyIntoFormData (allValues) {
                let totalPrice = 0
                let billMain = Object.assign(this.model, allValues.formValue)
                let detailArr = allValues.tablesValue[0].values
                billMain.type = '其它'
                billMain.subType = '拆卸单'
                billMain.defaultNumber = billMain.number
                for (let item of detailArr) {
                    totalPrice += item.allPrice - 0
                }
                billMain.totalPrice = totalPrice
                if (this.fileList && this.fileList.length > 0) {
                    billMain.fileName = this.fileList
                } else {
                    billMain.fileName = ''
                }
                if (this.model.id) {
                    billMain.id = this.model.id
                }
                billMain.status = this.billStatus
                return {
                    info: JSON.stringify(billMain),
                    rows: JSON.stringify(detailArr),
                }
            },
            onAdded (event) {
                const { row, target } = event
                getAction('/depot/findDepotByCurrentUser').then((res) => {
                    if (res.code === 200) {
                        let arr = res.data
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].isDefault) {
                                target.setValues([{ rowKey: row.id, values: { depotId: arr[i].id + '' } }])
                            }
                        }
                    }
                })
                if (target.rows.length >= 2) {
                    target.setValues([{ rowKey: row.id, values: { mType: '普通子件' } }])
                } else {
                    target.setValues([{ rowKey: row.id, values: { mType: '组合件' } }])
                }
            },
            handleImportForBom () {
                this.$refs.selectBomModal.showModal(undefined, '引入Bom清单')
            },
            onSelectBom (boms = []) {
                if (boms.length <= 0) {
                    return
                }

                let bom = boms[0]
                //插入列表
                this.materialTable.loading = true
                getBom(bom.id).then((responseData) => {
                    let bomInfo = responseData.data
                    let materialList = []
                    materialList.push({
                        barCode: bomInfo.barCode,
                        name: bomInfo.name,
                        operNumber: 1,
                        standard: bomInfo.standard,
                        model: bomInfo.model,
                        unit: bomInfo.unit
                    })

                    let bomMaterials = bomInfo.materials.map((bm) => {
                        return {
                            barCode: bm.barCode,
                            name: bm.name,
                            operNumber: bm.count,
                            standard: bm.standard,
                            model: bm.model,
                            unit: bm.unit,
                        }
                    })
                    materialList.push(...bomMaterials)

                    //todo 组合件重置默认配置为1
                    this.lastGroupItemOperNumber =  1;

                    let materialTable = this.$refs[this.refKeys[0]]
                    //clear
                    materialTable.initialize()
                    materialList.forEach((m) => {
                        materialTable.add(undefined, undefined, m)
                    })
                }).catch((error) => {
                    this.$message.error('获取bom物料清单失败')
                }).finally(() => {
                    this.materialTable.loading = false
                })
            },//组合键更新数量，普通子件同时改变数量
            onOperNumberValueChange (event) {
                const { type, row, column, value, target } = event
                //更新
                let isGroupItem = (row.mType == '组合件')
                let operValue = Number(value, 10)
                let isNumber = value != '' && !isNaN(operValue)
                if (isGroupItem && isNumber && operValue > 0) {
                    //获取上一次有效的值
                    let lastOperNumber = this.lastGroupItemOperNumber
                    //赋予新值
                    this.lastGroupItemOperNumber = operValue

                    let scale = operValue / lastOperNumber
                    let materialTableComponent = this.$refs[this.refKeys[0]]
                    let { values } = materialTableComponent.getValuesSync()
                    this.materialTable.dataSource = values
                    .map((r) => {
                        if (r.mType == '组合件') {
                            r.operNumber = operValue
                        } else {
                            let orignNumber = r.operNumber
                            r.operNumber = orignNumber * scale
                        }
                        return r
                    })

                }
            }
        }
    }
</script>
<style scoped>

</style>